import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';
//借助了react-focus-lock. 聚焦最后一个时候返回第一个
import FocusLock from 'react-focus-lock';
import {
  Wrapper,
  Header,
  StyledModal,
  HeaderText,
  CloseButton,
  Content,
  Backdrop,
} from './styledComponents/styled';
//过度动画
import { CSSTransition } from 'react-transition-group';
import '../myModal/styledComponents/anmate.css';

const myModal = ({ isShown, hide, modalContent, headerText, closeIcon }) => {
  const onKeyDown = (event) => {
    if (event.keyCode === 27 && isShown) {
      hide();
    }
  };
  useEffect(() => {
    isShown
      ? (document.body.style.overflow = 'hidden')
      : (document.body.style.overflow = 'unset');
    document.addEventListener('keydown', onKeyDown, false);
    return () => {
      document.removeEventListener('keydown', onKeyDown, false);
    };
  }, [isShown, onKeyDown]);
  const modal = (
    <>
      <Backdrop />
      <FocusLock>
        <Wrapper>
          <CSSTransition
            in={isShown}
            classNames="card"
            timeout={600}
            appear={true}
            unmountOnExit={true}
          >
            <StyledModal>
              <Header>
                <HeaderText>{headerText}</HeaderText>
                <CloseButton onClick={hide}>关闭{closeIcon}</CloseButton>
              </Header>
              <Content>{modalContent}</Content>
            </StyledModal>
          </CSSTransition>
        </Wrapper>
      </FocusLock>
    </>
  );
  return isShown ? createPortal(modal, document.body) : null;
};

export default myModal;
